//
//  FilesViewController.swift
//  PDF2PNG
//
//  Created by Jarvis on 08/05/2017.
//  Copyright © 2017 Jarvis. All rights reserved.
//

import UIKit
import Localize_Swift

class FilesViewController: TableViewController {

    var pdfItems = [[String: String]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "title".localized()
        
        self.view.backgroundColor = UIColor.white
        
        let leftItem = UIBarButtonItem(title: "Setting".localized(), style: .plain, target: self, action: #selector(leftItemPressed(_:)))
        self.navigationItem.leftBarButtonItem = leftItem;
        
        let rightItem = UIBarButtonItem(title: "Refresh".localized(), style: .plain, target: self, action: #selector(rightItemPressed(_:)))
        self.navigationItem.rightBarButtonItem = rightItem;
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
        
        rightItemPressed(rightItem)
    }
    
    @objc func leftItemPressed(_ buttonItem: UIBarButtonItem) {
        navigationController?.pushViewController(SettingViewController(), animated: true)
    }
    
    @objc func rightItemPressed(_ buttonItem: UIBarButtonItem) {
        pdfItems.removeAll();
        
        let fileName = "manual.pdf"
        let fileManager = FileManager.default
        let groupURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.pdf2png")
        let newFileURL = groupURL!.appendingPathComponent(fileName)
        
        let sourcePath = Bundle.main.path(forResource: fileName, ofType: nil)
        
        do {
            if !fileManager.fileExists(atPath: newFileURL.path) {
                try fileManager.copyItem(atPath: sourcePath!, toPath: newFileURL.path)
            }
            
            pdfItems.append(["fileName":"manual.pdf", "filePath":newFileURL.path, "createAt": String(format:"%lld", Date().timeIntervalSinceNow)])
            //        pdfItems.append(["fileName":"使用手册.pdf", "filePath":"manual.pdf", "createAt": String(format:"%lld", Date().timeIntervalSinceNow)])
            
        }catch {
            print("Copy file failed.")
        }
        
        

        
        let userDefault = UserDefaults(suiteName: "group.pdf2png");
        
        if let items = userDefault?.value(forKey: "pdfItems") {
            pdfItems.append(contentsOf: items as! [[String:String]])
        }
        
        tableView.reloadData();
        
        Tracker.refreshList()

    }
    
    func appendDefaultDocs() {
        
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return pdfItems.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        
        

        let item = pdfItems[indexPath.row]
        let fileName = item["fileName"]
        
        cell.textLabel?.text = fileName;
        cell.textLabel?.lineBreakMode = .byTruncatingMiddle
        cell.imageView?.image = UIImage(named: "thumb_pdf")
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        
        let convert = ConvertViewController()
        
        let item = pdfItems[indexPath.row]
        let fileName = item["fileName"]
        
        if let filePath = item["filePath"] {
            let pdfURL = URL(fileURLWithPath: filePath)
            convert.pdfURL = pdfURL
            self.navigationController?.pushViewController(convert, animated: true);
        }else {
            print("没有找到指定文件：\(String(describing: fileName))")
        }
        
        Tracker.openDoc(docName: fileName!)
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        let alertController = UIAlertController(title: "Warning", message: "Delete this file.", preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "YES", style: .default, handler: { (action) in
            let currentItem = self.pdfItems[indexPath.item]
            let userDefault = UserDefaults(suiteName: "group.pdf2png");
            
            if let items = userDefault?.value(forKey: "pdfItems") {
                var itemArray = items as! [[String:String]]
                for i in 0..<itemArray.count {
                    let item = itemArray[i]
                    let filePath = item["filePath"]
                    if filePath == currentItem["filePath"] {
                        itemArray.remove(at: i)
                        
                        let fileManager = FileManager.default
                        if fileManager.fileExists(atPath: filePath!) {
                            do {
                                try fileManager.removeItem(atPath: filePath!)
                                
                                userDefault?.set(itemArray, forKey: "pdfItems")
                                userDefault?.synchronize()
                            }catch {
                                Toast.showMessage(message: "Delete file failed.")
                                return
                            }
                        }
                        break
                    }
                }
            }

            self.pdfItems.remove(at: indexPath.item)
            tableView.deleteRows(at: [indexPath], with: .fade)
            
            Toast.showMessage(message: "Delete file successfully.")
        }))
        
        alertController.addAction(UIAlertAction(title: "NO", style: .cancel, handler: nil))
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}
